/*
 * ========================================================
 * Copyright(c) 2014 杭州龙骞科技-版权所有
 * ========================================================
 * 本软件由杭州龙骞科技所有, 未经书面许可, 任何单位和个人不得以
 * 任何形式复制代码的部分或全部, 并以任何形式传播。
 * 公司网址
 * http://www.hzdracom.com/
 * ========================================================
 */
package com.shwread.android.ui.page;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.NewActionHelp;
import com.ciko.code.bean.UserBean;
import com.ciko.code.constant.Constants;
import com.google.gson.reflect.TypeToken;
import com.netease.nim.demo.base.YXBaseActivity;
import com.shwread.android.qysw.activity.BaseSimpleActivity;
import com.shwread.android.qysw.activity.BookNotesActivity;
import com.shwread.android.qysw.activity.BookTicketActivity;
import com.shwread.android.qysw.activity.MainActivity;
import com.shwread.android.qysw.activity.MyCommentActivity;
import com.shwread.android.qysw.activity.MyHealthActivity;
import com.shwread.android.qysw.activity.NewLoginActivity;
import com.shwread.android.qysw.activity.WebViewActivity;
import com.shwread.android.qysw10000136.R;
import com.shwread.android.ui.dialog.ClearCacheDialog;
import com.shwread.android.ui.page.chat.SessionPage;
import com.shwread.android.ui.widget.CircleImageView;
import com.shwread.http.base.ObjectHttpResponseHandler;
import com.shwread.http.base.TextHttpResponseHandler;
import com.shwread.httpsdk.http.callback.ActionListener;
import com.shwread.httpsdk.http.callback.BaseAction;
import com.shwread.httpsdk.http.face.QryHaveNewCommentAction;
import com.tgx.tina.android.ipc.framework.IUIPage;

import org.apache.http.Header;
import org.geometerplus.android.util.QyreaderPerferencesUtil;

import java.io.File;
import java.lang.reflect.Type;
import java.util.Date;
import java.util.HashMap;

import base.tina.core.task.infc.ITaskResult;
import logic.bean.NewCommentInfo;
import logic.constants.Const;
import logic.constants.DefaultConsts;
import logic.util.DateUtil;
import logic.util.FileUtil;
import logic.util.PicassoUtil;
import logic.util.SDcardUtil;
import logic.util.Util;


/**
 * @Project： Lqyd_Android
 * @Title：PersionPage
 * @Description： 个人中心页面
 * @Author：wayne
 * @Date：2014年8月13日下午6:40:28
 */
public class PersonalPage
        extends
        AbstractUIPage<MainActivity>
        implements
        OnClickListener,
        ActionListener {
    private TextView tvPushSetIsOn;
    private Button btnBack;
    private CircleImageView ivHeader;
    private TextView tvName;
    private TextView tvClearCache;
    private Button btnEditName;
    private TextView tvTitle;
    private RelativeLayout rLayHealth;
    private RelativeLayout rLayNotes;
    private RelativeLayout rLayComments;
    private RelativeLayout rLayChangePwd;
    private RelativeLayout rLayPushSet;
    private RelativeLayout rLayClearCacheSet;
    private RelativeLayout rLayAbout;
    private RelativeLayout rlayBookTicket;
    private TextView tvbookTicketTime;
    private TextView tvCompanyNane, tvCompanyPhone;

    private Button btnChangeAccount;
    private UserBean user;
    private File diskCachePath;
    private long lastCheckNewCommentsTime = 0;
    private ImageView user_newcomments_iv;
    private ImageView ivUserGender;
    private TextView tvCity;

    private RelativeLayout rlayMyGoods, rlayProduct;                                             //电商我的商品
    private RelativeLayout rlayAddress;                                             //电商收货地址
    private ImageView imgMyGoodsDot;                                             //小红点

    private RelativeLayout rlayMyAppointment;                                         //点餐 我的预约
    private View vDividerGoods, vDividerComments, vDividerAddress;
    private HashMap<String, String> parameter_map = new HashMap<String, String>();
    private String url1 = "http://42.121.255.86/qyyd/file/fwbz/read.html";
    private String url2 = "http://42.121.255.86/qyyd/file/10000152cpsc/news.html";
    private String completedUrl;

    /**
     * <p>
     * Title:
     * </p>
     * <p>
     * Description:
     * </p>
     *
     * @param t
     */
    public PersonalPage(MainActivity t) {
        super(t);
    }

    @Override
    public <E extends Activity> View createView(E arg0, int arg1) {
        if (null != curMyView)
            return curMyView;
        curMyView = bActivity.getLayoutInflater().inflate(R.layout.user_info_setting, null);
        String url = "10000136".equals(Constants.enterpriseId) ? url1 : url2;
        final String addStr = url.indexOf("?") == -1 ? "?" : "&";
        completedUrl = url + addStr + "time=" + System.currentTimeMillis();
        initView();
        setListener();
        setCache();
        //预加载全国城市数据
        //		new Thread()
        //		{
        //			@Override
        //			public void run() {
        //				SelectCityDialog.initData(bActivity);
        //			}
        //		}.start();
        return curMyView;
    }

    void initView() {
        tvTitle = (TextView) curMyView.findViewById(R.id.common_header_name);
        tvTitle.setText("我的");
        btnBack = (Button) curMyView.findViewById(R.id.common_header_back);
        btnBack.setVisibility(View.VISIBLE);
        ivUserGender = (ImageView) curMyView.findViewById(R.id.userinfo_top_info_gender);
        tvCity = (TextView) curMyView.findViewById(R.id.userinfo_top_info_city);

        tvPushSetIsOn = (TextView) curMyView.findViewById(R.id.user_info_setting_push_tv);
        tvClearCache = (TextView) curMyView.findViewById(R.id.user_info_setting_clear_cache_tv);
        ivHeader = (CircleImageView) curMyView.findViewById(R.id.userinfo_header_img);
        tvName = (TextView) curMyView.findViewById(R.id.userinfo_name_et);
        btnEditName = (Button) curMyView.findViewById(R.id.change_user_name);
        rLayNotes = (RelativeLayout) curMyView.findViewById(R.id.userinfo_mynotes_rlay);
        //rLayNotes.setVisibility(View.VISIBLE);//如果是打的评论包，这行需要注释了
        rLayComments = (RelativeLayout) curMyView.findViewById(R.id.userinfo_mycomments_rlay);
        vDividerComments = curMyView.findViewById(R.id.userinfo_mycomments_divider);
        rLayComments.setVisibility(View.VISIBLE); //如果是打企业专区的包，这行需要注释了
        vDividerComments.setVisibility(View.VISIBLE);
        user_newcomments_iv = (ImageView) curMyView.findViewById(R.id.user_newcomments_iv);
        rLayChangePwd = (RelativeLayout) curMyView.findViewById(R.id.userinfo_changepwd_rlay);
        rLayPushSet = (RelativeLayout) curMyView.findViewById(R.id.userinfo_pushset_rlay);
        rLayClearCacheSet = (RelativeLayout) curMyView.findViewById(R.id.userinfo_clearcache_rlay);
        rLayAbout = (RelativeLayout) curMyView.findViewById(R.id.userinfo_about_rlay);
        btnChangeAccount = (Button) curMyView.findViewById(R.id.userinfo_change_account);
        rlayBookTicket = (RelativeLayout) curMyView.findViewById(R.id.userinfo_recharge_rlay);
        tvbookTicketTime = (TextView) curMyView.findViewById(R.id.user_info_setting_time_tv);
        tvCompanyNane = (TextView) curMyView.findViewById(R.id.user_info_setting_company_name);
        tvCompanyPhone = (TextView) curMyView.findViewById(R.id.user_info_setting_company_phone);
        rLayHealth = (RelativeLayout) curMyView.findViewById(R.id.userinfo_health_rlay);
        rlayProduct = (RelativeLayout) curMyView.findViewById(R.id.userinfo_product_rlay);
        //电商
        //		rlayMyGoods = (RelativeLayout) curMyView.findViewById(R.id.userinfo_mygoods_rlay);
        //		rlayAddress = (RelativeLayout) curMyView.findViewById(R.id.userinfo_address_rlay);
        //		vDividerAddress = curMyView.findViewById(R.id.userinfo_address_divider);
        //		vDividerGoods = curMyView.findViewById(R.id.userinfo_mygoods_divider);
        //		imgMyGoodsDot = (ImageView) curMyView.findViewById(R.id.user_mygoods_dot);

        //点餐
        //		rlayMyAppointment = (RelativeLayout) curMyView.findViewById(R.id.userinfo_myappointment_rlay);
        //		rlayMyAppointment.setVisibility(View.VISIBLE);
        //		rlayMyGoods.setVisibility(View.GONE);
        //		rlayAddress.setVisibility(View.GONE);
        //		vDividerAddress.setVisibility(View.GONE);
        //		vDividerGoods.setVisibility(View.GONE);
    }

    void setListener() {
        rlayProduct.setOnClickListener(this);
        btnBack.setOnClickListener(this);
        ivHeader.setOnClickListener(this);
        rLayNotes.setOnClickListener(this);
        rLayComments.setOnClickListener(this);
        rLayChangePwd.setOnClickListener(this);
        rLayPushSet.setOnClickListener(this);
        rLayClearCacheSet.setOnClickListener(this);
        rLayAbout.setOnClickListener(this);
        btnChangeAccount.setOnClickListener(this);
        btnEditName.setOnClickListener(this);
        rlayBookTicket.setOnClickListener(this);
        rLayHealth.setOnClickListener(this);
        //电商
        //		rlayMyGoods.setOnClickListener(this);
        //		rlayAddress.setOnClickListener(this);
        //
        //		rlayMyAppointment.setOnClickListener(this);
    }

    @Override
    public int enter(IUIPage<?> arg0) {
        //		new QryAccountInfoAction(context, this).start();
        NewActionHelp.qryAccountInfo(context, new MyHandler());
        getHaveNewComments(); //如果是打企业专区的包，这行需要注释了
        setPush(QyreaderPerferencesUtil.getInstance(bActivity, Const.phone_number).getPushMessage());
        getHaveNewestOrderInfor();
        return 0;
    }

    @Override
    public int leave(IUIPage<?> arg0) {
        return 0;
    }

    @Override
    public void notifyView(int arg0, Bundle arg1) {
        switch (arg0) {
            case 123:
                tvClearCache.setText("0M");
                break;
            //			case 124:
            //				tvbookTicketTime.setText("还剩"+""+ "个月");
            //				break;
            default:
                break;
        }
    }

    private void setPush(boolean b) {
        tvPushSetIsOn.setText(b ? "开启" : "关闭");
        tvPushSetIsOn.setTextColor(bActivity.getResources().getColor(b ? R.color.edit_font_color : R.color.edit_hint_color));
    }

    /***
     * 设置书券剩余时间
     */
    private void setbBookTicketMounth(long time) {

        tvbookTicketTime.setText(bActivity.getResources().getString(R.string.user_info_setting_recharge_value, Util.getFormatTime("yy年MM月", time)));

    }

    @Override
    public void setStatus(int arg0) {

    }

    @Override
    public View updateView(int arg0, ITaskResult arg1) {
        setPush(QyreaderPerferencesUtil.getInstance(bActivity, Const.phone_number).getPushMessage());
        return null;
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.userinfo_product_rlay:
                Intent intent2 = new Intent(bActivity, WebViewActivity.class);
                intent2.putExtra(DefaultConsts.title_s, "产品手册");
                intent2.putExtra(DefaultConsts.req_url_s, completedUrl);
                bActivity.startActivity(intent2);
                break;
            case R.id.common_header_back:
                bActivity.onBackPressed();
                break;
            case R.id.userinfo_header_img:
            case R.id.change_user_name:
                PersonalInfoPage page = new PersonalInfoPage(bActivity);
                page.setUser(user);
                bActivity.changePage(page, DEFAULT_STATUS);
                break;
            case R.id.userinfo_mynotes_rlay:
                bActivity.startActivity(new Intent(bActivity, BookNotesActivity.class));
                break;
            case R.id.userinfo_mycomments_rlay:
                bActivity.startActivity(new Intent(bActivity, MyCommentActivity.class));
                if (lastCheckNewCommentsTime > 1000) {//是一个有效时间
                    QyreaderPerferencesUtil.getInstance(context, Const.phone_number).setLastCheckTime(lastCheckNewCommentsTime);
                    lastCheckNewCommentsTime = 0;
                }
                user_newcomments_iv.setVisibility(View.GONE);
                break;
            case R.id.userinfo_changepwd_rlay:
                bActivity.changePage(ChangePasswordPage.getInstance(bActivity), DEFAULT_STATUS);
                break;
            case R.id.userinfo_pushset_rlay:
                bActivity.changePage(PushSettingPage.getInstance(bActivity), DEFAULT_STATUS);
                break;
            case R.id.userinfo_clearcache_rlay:
                if (tvClearCache.getText().equals("0M")) {
                    Util.showToast(bActivity, "暂无缓存！");
                } else {
                    ClearCacheDialog dialog = new ClearCacheDialog(bActivity);
                    dialog.show();
                }
                //Util.showToast(bActivity, "敬请期待清除缓存...");
                break;
            case R.id.userinfo_about_rlay:
                bActivity.changePage(AboutPage.getInstance(bActivity), DEFAULT_STATUS);
                break;
            case R.id.userinfo_change_account:
                clickChangeAccount();
                break;
            case R.id.userinfo_recharge_rlay:
                Intent intent = new Intent(bActivity, BookTicketActivity.class);
                intent.putExtra(DefaultConsts.from_page, DefaultConsts.TAG_PERSONAL);
                bActivity.startActivity(intent);
                break;
            case R.id.userinfo_health_rlay:
                Intent intent1 = new Intent(bActivity, MyHealthActivity.class);
                bActivity.startActivity(intent1);
                break;
//			case R.id.userinfo_mygoods_rlay://电商我的商品
//				Intent myGoodsIntent = new Intent(bActivity, MyGoodsActivity.class);
//				bActivity.startActivity(myGoodsIntent);
//				imgMyGoodsDot.setVisibility(View.GONE);
//				QyreaderPerferencesUtil.getInstance(context, NewActionHelp.getAccount()).setLastCheckTimeECommerce(new Date().getTime());
//				break;
//			case R.id.userinfo_address_rlay://电商收货地址
//				Intent addressInfiListIntent = new Intent(bActivity, AddressInfoListActivity.class);
//				bActivity.startActivity(addressInfiListIntent);
//				break;
//			case R.id.userinfo_myappointment_rlay:
//				//				Utils.showToast(bActivity, "您点击了我的预约");
//				Intent myAppointmentIntent = new Intent(bActivity, MyAppointmentListActivity.class);
//				bActivity.startActivity(myAppointmentIntent);
//				break;
            default:
                break;
        }
    }

    private void setCache() {
        diskCachePath = SDcardUtil.getImagePath();
        long size = 0;
        try {
            size = FileUtil.getFolderSize(diskCachePath);
        } catch (Exception e) {
        }
        String sizeStr = FileUtil.FormetFileSize(size);
        tvClearCache.setText(sizeStr);
    }

    void clickChangeAccount() {
        //IM账号登出
        //		NIMClient.getService(AuthService.class).logout();

        SessionPage.isFirstIn = 2;
        BaseSimpleActivity.clearNotification(bActivity, -1);
        BaseSimpleActivity.exit();
        YXBaseActivity.exit();
        Intent intent = new Intent(bActivity, NewLoginActivity.class);
        bActivity.startActivity(intent);
        bActivity.finish();

    }

    class MyHandler
            extends
            ObjectHttpResponseHandler<UserBean> {

        @Override
        public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {

        }

        @Override
        public void onSuccess(int statusCode, Header[] headers, UserBean object, String responseString) {
            user = object;
            updateUserInfoUI(user);
        }

        @Override
        public Type getType() {
            return new TypeToken<UserBean>() {
            }.getType();
        }
    }

    private void updateUserInfoUI(UserBean user) {
        if (null == user)
            return;
//		ivHeader.setImageUrl(user.getHeadImage(), R.drawable.user_head_img, R.drawable.user_head_img);
        PicassoUtil.load(context, user.getHeadImage(), R.drawable.user_head_img, ivHeader);
        tvName.setText(user == null ? Const.phone_number : user.getNickName());
        if (null != user && !TextUtils.isEmpty(user.getSex())) {
            ivUserGender.setImageResource(user.getSex().equals("男") || user.getSex().equals("0") ? R.drawable.ic_gender_men : R.drawable.ic_gender_ms);
            ivUserGender.setVisibility(View.VISIBLE);
        }
        tvCity.setText(user == null || TextUtils.isEmpty(user.getHomeTown()) ? "" : ("| " + user.getHomeTown()));
        setbBookTicketMounth(user.getCloseTime());
    }

    @Override
    public void OK(Object obj) {
        if (Util.isEmpty(obj.toString()))
            return;
        user = (UserBean) obj;
        bActivity.getUIHandler().post(new Runnable() {
            @Override
            public void run() {
                updateUserInfoUI(user);
            }
        });
    }

    @Override
    public void ERROR(int resultCode, String message) {

    }

    @Override
    public void HTTPERROR(int statusCode) {

    }

    private void getHaveNewComments() {
        long lastCheckTime = QyreaderPerferencesUtil.getInstance(context, Const.phone_number).getLastCheckTime();
        String strLastCheckTime = DateUtil.getDateTime(new Date(lastCheckTime));
        QryHaveNewCommentAction haveNewComments = new QryHaveNewCommentAction(context, lastCheckTime, new HaveNewCommentsActionListener());
        haveNewComments.start();
    }

    /**
     * 检测是否有我的新评论
     */
    private class HaveNewCommentsActionListener
            extends
            BaseAction {
        @SuppressWarnings("unchecked")
        @Override
        public void OK(Object obj) {
            NewCommentInfo newCommentsInfo = (NewCommentInfo) obj;
            if (newCommentsInfo == null) {
                bActivity.getUIHandler().post(new Runnable() {
                    @Override
                    public void run() {
                        //调用出错
                    }
                });
                return;
            }

            boolean haveNew = "y".equalsIgnoreCase(newCommentsInfo.haveNewComment) ? true : false;
            if (haveNew) {
                lastCheckNewCommentsTime = newCommentsInfo.lastQryTime;
                String lastQryTime = DateUtil.getDateTime(new Date(lastCheckNewCommentsTime));//为了调试
                //刷新UI
                bActivity.getUIHandler().post(new Runnable() {
                    @Override
                    public void run() {
                        //显示红点点
                        user_newcomments_iv.setVisibility(View.VISIBLE);
                    }
                });
            }
        }

        @Override
        public void onError() {
            super.onError();
            Util.showToast(context, "检查是否有我的新评论失败");
        }
    }

    /**
     * 电商红点
     */
    private void getHaveNewestOrderInfor() {
        QyreaderPerferencesUtil sharePerferencesUtil = QyreaderPerferencesUtil.getInstance(context, NewActionHelp.getAccount());
        NewActionHelp.qryHaveNewestOrderInfor(context, sharePerferencesUtil.getLastCheckTimeECommerce(), new HaveNewestOrderInforHandler());
    }

    private class HaveNewestOrderInforHandler
            extends
            TextHttpResponseHandler {

        @Override
        public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
            // TODO Auto-generated method stub

        }

        @Override
        public void onSuccess(int statusCode, Header[] headers, String responseString) {
            //			try
            //			{
            //				if (Boolean.parseBoolean(JSONUtil.getString(responseString)))
            //				{
            //					imgMyGoodsDot.setVisibility(View.VISIBLE);
            //				}
            //			}
            //			catch (JSONException e)
            //			{
            //				// TODO Auto-generated catch block
            //				e.printStackTrace();
            //			}

        }

    }
}
